package com.cutefool.zero.code.admin.meta.model.web;

import com.cutefool.core.res.Message;
import com.cutefool.core.res.Response;
import com.cutefool.core.res.ResponseCode;
import com.cutefool.dsl.mybatis.core.dsl.builder.UpdateDsl;
import com.cutefool.dsl.mybatis.core.dsl.operation.CuteCurdOperation;
import com.cutefool.zero.code.admin.consts.Constants;
import com.cutefool.zero.code.admin.meta.model.dto.ModelBasicDTO;
import com.cutefool.zero.code.admin.meta.model.service.ModelService;
import com.cutefool.zero.code.core.domain.Model;
import jakarta.annotation.Resource;
import org.mybatis.dynamic.sql.SqlBuilder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(Constants.API_PREFIX)
public class ModelDbController {

    @Resource
    private ModelService modelService;

    @Resource
    private CuteCurdOperation<Model> cuteCurdOperation;

    /**
     * 更新
     *
     * @param id  id
     * @param dto dto
     * @return Response<Long>
     **/
    @PostMapping("/update/models/{id}")
    public Response<?> update(@PathVariable Long id, @RequestBody @Validated ModelBasicDTO dto) {
        boolean b = this.modelService.validateName(id, dto.getName());
        if (!b) {
            return Response.failure(ResponseCode.API_ERROR.getCode(), String.format(Message.MESSAGE_DATA_EXISTS, dto.getName()));
        }
        UpdateDsl<Model> updateDsl = UpdateDsl.newInstance(Model.instance()).entity(dto).where(w -> w.and(Model.instance().id(), SqlBuilder.isEqualTo(id)));
        this.cuteCurdOperation.updateSelective(updateDsl);
        // 处理变更脚本
        return Response.ok(id);
    }
}
